package com.ctz.commonframe.http;

import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;
import org.xutils.common.Callback.Cancelable;
import org.xutils.common.Callback.CommonCallback;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.ctz.commonframe.utils.Logger;

import android.text.TextUtils;

public class HttpClient {
	private static final String TAG = "HttpClient";

	private static final String RESPONSE_SUCCESS = "1";

	public interface OnHttpResultListener<T> {
		void onResult(boolean isSuccess, List<T> data, String msg);
	}

	public static <T> Cancelable request(String url, String requestBody, final Class<T> clazz,
			final OnHttpResultListener<T> listener) {
		Logger.e(TAG, "【requestUrl】" + url);
		Logger.e(TAG, "【requestBody】" + requestBody);
		return x.http().request(HttpMethod.POST, buildParams(url, requestBody), new CommonCallback<ResponseEntity>() {

			@Override
			public void onCancelled(CancelledException arg0) {

			}

			@Override
			public void onError(Throwable arg0, boolean arg1) {
				Logger.e(TAG, "【responseError】" + arg0.getLocalizedMessage());
				listener.onResult(false, null, "访问服务器失败");
			}

			@Override
			public void onFinished() {

			}

			@Override
			public void onSuccess(ResponseEntity arg0) {
				parseResult(arg0, clazz, listener);
			}
		});
	}

	public <T> Cancelable request(String url, Map<String, Object> map, Class<T> clazz,
			final OnHttpResultListener<T> listener) {
		return request(url, new JSONObject(map).toString(), clazz, listener);
	}

	public <T> Cancelable request(String url, Object obj, Class<T> clazz, final OnHttpResultListener<T> listener) {
		return request(url, JSON.toJSONString(obj), clazz, listener);
	}

	private static RequestParams buildParams(String url, String requestBody) {
		RequestParams params = new RequestParams(url);
		params.setAsJsonContent(true);
		JSONObject jobj = new JSONObject();
		try {
			jobj.put("obj", requestBody);
			params.setBodyContent(jobj.toString());
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return params;
	}

	private static <T> void parseResult(ResponseEntity entity, Class<T> clazz, final OnHttpResultListener<T> listener) {
		if (RESPONSE_SUCCESS.equals(entity.RecordStatus)) {
			if (clazz == null) {
				listener.onResult(true, null, null);
			} else {
				List<T> list = JSONArray.parseArray(entity.RecordDetail, clazz);
				listener.onResult(true, list, null);
			}
		} else {
			listener.onResult(false, null, TextUtils.isEmpty(entity.RecordRemark) ? "访问服务器失败" : entity.RecordRemark);
		}
	}
}
